package com.bos.realm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.bos.bean.Function;
import com.bos.bean.User;
import com.bos.dao.FunctionDao;
import com.bos.dao.UserDao;
import com.bos.dao.impl.FunctionDaoImpl;

public class BosRealm extends AuthorizingRealm {

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private FunctionDao functionDao;
	
	//认证
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		UsernamePasswordToken userToken = (UsernamePasswordToken) token;
		String username = userToken.getUsername();
		//查询数据库  如果通过用户名查询到了用户
		User user = userDao.findUserByUserName(username);
		if(user == null){
			//没查询到
			return null;
		}
		// 验证密码   第一个参数  是认证的对象   user.getPassword()  == token的password  就代表认证成功
		AuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
		return info;
	}
	
	//授权   缓存
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//批量的添加权限添加权限
		//通过用户来查询 当前所具备的权限
		//如果用户名等于 admin  超级管理员
		//通过shiro框架获取当前登录的User对象
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		List<Function> functions = new ArrayList<>();
		if(user.getUsername().equals("admin")){
			//查询所有的权限
			functions = functionDao.getAll();
		}else{
			//1. 通过用户ID 查询 角色  通过角色查询权限
			functions = functionDao.findByUserId(user.getId());
		}
		//批量添加
		for (Function function : functions) {
			//添加权限给SimpleAuthorizationInfo  给授权的对象
			info.addStringPermission(function.getCode());
		}
		//TODO 查询数据库获取当前用户对应的角色  和角色对应的权限  在添加权限
		return info;
	}
	

}
